package com.hxzy.config.security;

import com.hxzy.common.util.TokenService;
import com.hxzy.controller.login.resp.AdminLoginResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义的Filter，验证令牌的
 */
@Component
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        AdminLoginResp adminLoginUser = this.tokenService.getAdminLoginUser(request);

        if(adminLoginUser!=null){            //构造一个
            UsernamePasswordAuthenticationToken  token=new UsernamePasswordAuthenticationToken(adminLoginUser,null,adminLoginUser.getAuthorities());
            token.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            //放到ThreadLoal本地线程池中
            SecurityContextHolder.getContext().setAuthentication(token);
        }

        //放行给其它的拦截器用   UsernamePasswordAuthenticationFilter
        filterChain.doFilter(request,response);

    }



}
